package com.xiaoma.fitz.service;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dexcoder.commons.pager.Pager;
import com.dexcoder.dal.JdbcDao;
import com.dexcoder.dal.build.Criteria;
import com.dexcoder.dal.spring.page.PageControl;
import com.xiaoma.fitz.domain.User;
import com.xiaoma.fitz.dto.QueryUserParams;

@Service
public class UserService {

    @Autowired
    private JdbcDao jdbcDao;
    
    public Pager findAll(int currentPage, int itemsPerPage) {
        PageControl.performPage(currentPage, itemsPerPage);
        jdbcDao.queryList(new User());
        return PageControl.getPager();
        
    }
    
    public Pager findUsers(QueryUserParams params) {
    	PageControl.performPage(params.getiDisplayStart()/params.getiDisplayLength() + 1, params.getiDisplayLength());
    	Criteria c = Criteria.select(User.class);
    	if (StringUtils.isNotBlank(params.getName())) {
    		String name = "%" + params.getName().trim() + "%";
    		c.and("name","like", new Object[]{name});
    	}
    	if (params.getGender() != null) {
    		c.and("gender", new Object[]{params.getGender()});
    	}
    	if (StringUtils.isNotBlank(params.getStartDate())) {
    		c.and("birthday", ">=", new Object[]{params.getStartDate()});
    	}
    	if (StringUtils.isNotBlank(params.getEndDate())) {
    		c.and("birthday", "<=", new Object[]{params.getEndDate()});
    	}
    	c.desc("id");
    	jdbcDao.queryList(c);
    	return PageControl.getPager();
    	
    }
    
    public void save(User user) {
    	user.setCreatedAt(new Date());
        jdbcDao.save(user);
    }
    
    public void delete(long id) {
        jdbcDao.delete(User.class, id);
    }
    
    public void update(User user) {
        jdbcDao.update(user);
    }
    
    public User getById(long id) {
        return jdbcDao.get(User.class, id);
    }
    
    public User findByNameAndPwd(String name, String password) {
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        return jdbcDao.querySingleResult(user);
    }
}
